<template>
  <div id="container" class="box">
    <button id="drawline">test</button>
    <!-- <!-- <div style="z-index:999;width:200px;height:200px;"> -->
      <!-- <el-table :data="positionsForUse"> 
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column label="经度" width="150">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.lng"
              @change="changePosition(scope.$index)"
            ></el-input> </template
        ></el-table-column>
        <el-table-column label="纬度" width="200">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.lat"
              @change="changePosition(scope.$index)"
            ></el-input> </template
        ></el-table-column>
        <el-table-column label="高度" width="200">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.alt"
              @change="changePosition(scope.$index)"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column width="200">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete"  @click.native.prevent="deleteRow(scope.$index)" circle></el-button>
          </template>
        </el-table-column>
         <el-table-column property="address" label="地址"></el-table-column> 
      </el-table>
       -->
    <div class="menubox">
      <el-tooltip class="item" effect="light" content="定位" placement="top">
        <el-popover placement="right" width="200" trigger="click" title="定位">
          <div>
            <el-input placeholder="请输入经度" v-model="in_lon" clearable>
            </el-input>
            <el-input placeholder="请输入纬度" v-model="in_lat" clearable>
            </el-input>
            <el-button type="primary" @click="goTo">搜索</el-button>
          </div>
          <el-button slot="reference"
            ><i
              class="el-icon-location-information"
              style="font-size:20px;"
            ></i>
          </el-button>
        </el-popover>
      </el-tooltip>
      <br />
      <el-tooltip
        class="item"
        effect="light"
        content="清空所有标记"
        placement="top"
      >
        <el-popover placement="right" width="200" v-model="clear_visible">
          <p>确定清除屏幕上所有标记吗？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="visible = false"
              >取消</el-button
            >
            <el-button type="primary" size="mini" @click="clear"
              >确定</el-button
            >
          </div>
          <el-button slot="reference"
            ><i class="el-icon-delete-solid" style="font-size:20px;"></i>
          </el-button>
        </el-popover>
      </el-tooltip>
      <br />

      <el-tooltip class="item" effect="light" content="测量" placement="top">
        <el-popover placement="right" width="200" trigger="click" title="测量">
          <div>
            <div style="margin: 15px 0;">
              <el-button type="primary" @click="measureLineSpace"
                >测量距离</el-button
              ><br /><br />
              <el-button type="primary" @click="measureAreaSpace"
                >测量面积</el-button
              >
            </div>
          </div>
          <el-button slot="reference"
            ><i class="el-icon-edit-outline" style="font-size:20px;"></i>
          </el-button>
        </el-popover>
      </el-tooltip>
      <br />
      <el-tooltip class="item" effect="light" content="标绘" placement="top">
        <el-popover placement="right" width="200">
          <div>
            <span style="font-weight:bolder;">右键结束标记</span>
            <br /><br />
            &nbsp;
            <el-button id="pointBtn">画点</el-button>
            <el-button id="lineBtn" @click="drawLineString">画线</el-button>
            <el-button id="polyBtn">画面</el-button>
            <el-button id="rectBtn">画矩形</el-button>
            <el-button id="circleBtn">画圆</el-button>
            <el-button id="clearBtn">清除</el-button>
          </div>

          <el-button slot="reference" @click="showDrawViewer = showDrawViewer"
            ><i class="el-icon-s-flag" style="font-size:20px;"></i
          ></el-button>
        </el-popover>
      </el-tooltip>
      <br />
      <el-tooltip
        class="item"
        effect="light"
        content="绘制航线"
        placement="top"
      >
        <el-popover placement="right" title="标题" width="200" disabled>
          <el-button slot="reference" @click="drawAirway"
            ><i class="el-icon-s-promotion" style="font-size:20px;"></i
          ></el-button>
        </el-popover>
      </el-tooltip>
      <br />
      <el-tooltip
        class="item"
        effect="light"
        content="添加模型"
        placement="top"
      >
        <el-popover placement="right" width="200" trigger="click">
          <div>
            模型列表 (右键结束标记)
            <div class="planebox" @click="selectPlane">
              <img src="plane.jpg" alt="" />
            </div>
          </div>
          <el-button slot="reference"
            ><i class="el-icon-edit" style="font-size:20px;"></i
          ></el-button>
        </el-popover> </el-tooltip
      ><br />

      <el-tooltip
        class="item"
        effect="light"
        content="其他功能"
        placement="top"
      >
        <el-popover
          placement="right"
          width="200"
          trigger="click"
          title="其他功能"
        >
          <div>
            <div style="margin: 15px 0;"></div>
            <el-checkbox v-model="showChinas" @change="showChina"
              >中国国界</el-checkbox
            >
            <el-checkbox v-model="showBirds" @change="showBird"
              >行政鹰眼图</el-checkbox
            >
          </div>
          <el-button slot="reference"
            ><i class="el-icon-menu" style="font-size:20px;"></i>
          </el-button>
        </el-popover>
      </el-tooltip>
      <br />
    </div>

    <div id="cesiumContainer">
      <button @click="draw">绘制</button>
      <button id="clear" style="color: white;" class="tool-item">关闭</button>
    </div>
    <div id="position">
      &nbsp;
      <div style="width: 200px;margin-left:50px;">经度:{{ longitude }}</div>
      &nbsp;
      <div style="width: 200px;">纬度:{{ latitude }}</div>
      <div style="width: 200px;">视角高度:{{ altitude }}</div>
      <div style="width: 200px;">海拔:{{ elevation }}</div>
    </div>
    <cesiumDrawViewer
      v-show="showDrawViewer"
      :extendMarkerImage="imags"
      ref="marker"
      :extendMarkerModel="model"
      @closeEvent="showDrawViewer = false"
    ></cesiumDrawViewer>
    <div id="eye" v-show="showBirds"></div>
  </div>
</template>

<script>
import { create } from "./DrawTransformCurve";
import { createEye } from "./Cesium2DLinkage3DUtil";
import * as L from "leaflet";
import $ from "jquery";
import cesiumDrawViewer from "@/components/cesiumDrawViewer";
import "cesium-draw/dist/theme/default.css";
import CesiumNavigation from "cesium-navigation-es6";
export default {
  name: "my-component",
  data() {
    return {
      record: -1,
      test_positions: [],
      point_positions: [],
      url: "http://localhost:3000/models/CesiumAir/Cesium_Air.glb",
      modelList: [
        {
          title: "CesiumAir",
          url: "http://localhost:3000/models/CesiumAir/Cesium_Air.glb",
        },
        {
          title: "CesiumMan",
          url: "http://localhost:3000/models/CesiumMan/Cesium_Man.glb",
        },

        {
          title: "GroundVehicle",
          url: "http://localhost:3000/models/GroundVehicle/GroundVehicle.glb",
        },
      ],
      Cesium: "",
      view: "",
      czml: [],

      longitude: "",
      latitude: "",
      altitude: "",
      elevation: "",

      dataSourcePromise: "",
      i: "",
      a: "",
      data: [],
      start: "",
      stop: null,
      viewer: "",
      position: {
        lon: 117.224,
        lat: 31.819,
        alt: 0,
      },
      rotates: {
        heading: 0,
        pitch: 0,
        roll: 0,
      },
      drawTransformCurve: "",
      imageryViewModels: [],
      handler: "",

      showChinas: false,
      China: "",

      showBirds: "",
      overMap: "",
      circle: "",
      removeImageryLayers: [],

      plane1: false,

      imags: [
        "./static/images/markers/1.png",
        "./static/images/markers/2.png",
        "./static/images/markers/3.png",
        "./static/images/markers/4.png",
        "./static/images/markers/5.png",
        "./static/images/markers/6.png",
        "./static/images/markers/7.png",
        "./static/images/markers/8.png",
        "./static/images/markers/5.png",
        "./static/images/markers/6.png",
      ],
      model: [
        { id: "model0", name: "木塔", url: "static/model/Wood_Tower.gltf" },
        { id: "model1", name: "人", url: "static/model/Cesium_Man.gltf" },
      ],

      in_lon: "",
      in_lat: "",

      clear_visible: false,
      showDrawViewer: false,
      leftDownFlag: false,
      ErectLinePositions: {},
      pointDraged: [],
      positionsForUse:[],
    };
  },
  components: { cesiumDrawViewer },
  mounted() {
    this.Cesium = this.cesium;
    let Cesium = this.Cesium;

    // this.viewer = new this.Cesium.Viewer("cesiumContainer", {
    //     //baseLayerPicker: false,
    //     timeline: false,
    //     //   homeButton: false,
    //     fullscreenButton: false,
    //     animation:false,
    //     infoBox: false,
    //     // sceneModePicker: false,
    //     navigationInstructionsInitiallyVisible: false,
    //     //  navigationHelpButton: false,
    //     shouldAnimate: true,

    //     //Credits Display:false,
    //     imageryProvider: new this.Cesium.UrlTemplateImageryProvider({
    //     url: "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
    //     // url:"http://localhost:3000/odm_orthophoto_titles/odm_orthophoto.original/{z}/{x}/{y}.png"
    //     }),
    // });
    // this.viewer._cesiumWidget._creditContainer.style.display = "none";

    var imageryViewModels = [];

    var bingMap = new Cesium.ProviderViewModel({
      name: "Bing Maps",
      iconUrl: "./tianditu1.jpg",
      tooltip: "Bing Maps aerial imagery",
      creationFunction: function() {
        return new Cesium.BingMapsImageryProvider({
          url: "https://dev.virtualearth.net",
          key:
            "AsbS67vJcc0bl4qO9HeC3_aZd42Gowdz-gGcsMER0JxtWr7nbRH5UnvLYLb-2rNF",
          mapStyle: Cesium.BingMapsStyle.AERIAL,
        });
      },
    });
    imageryViewModels.push(bingMap);

    var tiandituyx = new Cesium.ProviderViewModel({
      name: "天地图影像",
      tooltip: "天地图影像及中文标注数据",
      iconUrl: "./tianditu1.jpg",
      creationFunction: function() {
        var mapsources = [];
        var yx = new Cesium.WebMapTileServiceImageryProvider({
          url:
            "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=8b207a527da69c7a32f636801fa194d4",
          layer: "tdtBasicLayer",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "GoogleMapsCompatible",
          show: false,
        });
        var jd = new Cesium.WebMapTileServiceImageryProvider({
          url:
            "http://t0.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=8b207a527da69c7a32f636801fa194d4",
          layer: "tiandituImgMarker",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "tiandituImgMarker",
          show: true,
          maximumLevel: 16,
        });
        mapsources.push(yx, jd);
        return mapsources;
      },
    });
    imageryViewModels.push(tiandituyx);
    var tianditujd = new Cesium.ProviderViewModel({
      name: "天地图街道",
      tooltip: "天地图街道数据",
      iconUrl: "./tianditu2.jpg",
      creationFunction: function() {
        return new Cesium.WebMapTileServiceImageryProvider({
          url:
            "http://t0.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=8b207a527da69c7a32f636801fa194d4",
          layer: "tdtVecBasicLayer",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "GoogleMapsCompatible",
          show: false,
        });
      },
    });
    imageryViewModels.push(tianditujd);
    var tiandituzj = new Cesium.ProviderViewModel({
      name: "天地图中文标注",
      tooltip: "天地图中文标注数据",
      iconUrl: "./tianditu3.jpg",
      creationFunction: function() {
        return new Cesium.WebMapTileServiceImageryProvider({
          url:
            "http://t0.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=8b207a527da69c7a32f636801fa194d4",
          layer: "tiandituImgMarker",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "tiandituImgMarker",
          show: true,
          maximumLevel: 16,
        });
      },
    });
    imageryViewModels.push(tiandituzj);
    // var tianditugjx=new Cesium.ProviderViewModel({
    //     name:"天地图国界线",
    //     tooltip:"天地图国界线数据",
    //     iconUrl:"./sampleData/images/tianditu.jpg",
    //     creationFunction: function() {
    //       return new Cesium.WebMapTileServiceImageryProvider({
    //         url:
    //           "https://t0.tianditu.gov.cn/ibo_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=ibo&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=8b207a527da69c7a32f636801fa194d4",
    //         layer: "tiandituImg",
    //         style: "default",
    //         format: "image/jpeg",
    //         tileMatrixSetID: "tiandituImg",
    //         show: true,
    //         maximumLevel: 16
    //       })
    //     }
    // });
    // imageryViewModels.push(tianditugjx)

    var gaode = new Cesium.ProviderViewModel({
      name: "高德地图",
      tooltip: "高德地图",
      iconUrl: "./gaode1.jpeg",
      creationFunction: function() {
        return new Cesium.UrlTemplateImageryProvider({
          url:
            "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
          layer: "gaodelayer",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "gaode",
          show: true,
          maximumLevel: 16,
        });
      },
    });
    imageryViewModels.push(gaode);

    var lixian = new Cesium.ProviderViewModel({
      name: "离线地图",
      tooltip: "离线地图",
      iconUrl: "./gaode1.jpeg",
      creationFunction: function() {
        return new Cesium.UrlTemplateImageryProvider({
          url: "http://localhost:3000/_alllayers/{z}/{x}/{y}.png",
          layer: "gaodelayer",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "gaode",
          show: true,
          maximumLevel: 16,
        });
      },
    });
    imageryViewModels.push(lixian);

    var gaode2 = new Cesium.ProviderViewModel({
      name: "高德地图卫星",
      tooltip: "高德地图",
      iconUrl: "./gaode2.jpg",
      creationFunction: function() {
        return new Cesium.UrlTemplateImageryProvider({
          url:
            "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
          layer: "gaode2layer",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "gaode2",
          show: true,
          maximumLevel: 16,
        });
      },
    });
    imageryViewModels.push(gaode2);
    this.viewer = new Cesium.Viewer("cesiumContainer", {
      navigationHelpButton: false, //控制右上角第五个位置的导航帮助按钮
      animation: false, //控制左下角的动画器件
      timeline: false, //控制下方时间线
      imageryProviderViewModels: imageryViewModels,
      selectedImageryProviderViewModel: bingMap,
      //Credits Display:false,

      //
      terrainProvider: Cesium.createWorldTerrain(),
    });
    this.viewer.scene.globe.depthTestAgainstTerrain = false;
    this.viewer._cesiumWidget._creditContainer.style.display = "none";
    this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
      Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    );

    //配置项
    let options = 
    {enableCompass:true,
    enableZoomControls:true,
    enableCompassOuterRing:true,
    enableDistanceLegend:true};

//添加罗盘
    new CesiumNavigation(this.viewer, options);

    // var viewer=new Cesium.Viewer("cesiumContainer",{
    //   baseLayerPicker : true,//是否显示图层选择器
    //   imageryProviderViewModels:imageryViewModels,
    //   selectedImageryProviderViewModel:tianditujd
    // })
    //  this.$refs.drawManager.init(this.viewer)
    this.computePositon();
    this.beginBird();

    var _this = this;
    $("#pointBtn").bind("click", function() {
      _this.drawPoint(function(positions) {
        var wgs84_positions = [];
        for (var i = 0; i < positions.length; i++) {
          var wgs84_point = _this.Cartesian3_to_WGS84({
            x: positions[i].x,
            y: positions[i].y,
            z: positions[i].z,
          });
          wgs84_positions.push(wgs84_point);
        }
        console.log(wgs84_positions);
      });
    });

    $("#polyBtn").bind("click", function() {
      _this.drawPolygon(function(positions) {
        var wgs84_positions = [];
        for (var i = 0; i < positions.length; i++) {
          var wgs84_point = _this.Cartesian3_to_WGS84({
            x: positions[i].x,
            y: positions[i].y,
            z: positions[i].z,
          });
          wgs84_positions.push(wgs84_point);
        }
        console.log(wgs84_positions);
      });
    });

    $("#rectBtn").bind("click", function() {
      _this.drawRect(function(positions) {
        var wgs84_positions = [];
        for (var i = 0; i < positions.length; i++) {
          var wgs84_point = _this.Cartesian3_to_WGS84({
            x: positions[i].x,
            y: positions[i].y,
            z: positions[i].z,
          });
          wgs84_positions.push(wgs84_point);
        }
        console.log(wgs84_positions);
      });
    });

    $("#circleBtn").bind("click", function() {
      _this.circleDraw(function(positions) {
        var wgs84_positions = [];
        for (var i = 0; i < positions.length; i++) {
          var wgs84_point = _this.Cartesian3_to_WGS84({
            x: positions[i].x,
            y: positions[i].y,
            z: positions[i].z,
          });
          wgs84_positions.push(wgs84_point);
        }
        console.log(wgs84_positions);
      });
    });

    $("#clearBtn").bind("click", function() {
      _this.clearHandle();
    });

    this.$refs.marker.init(_this.viewer);

    this.viewer.screenSpaceEventHandler.setInputAction(
      _this.leftDownAction,
      Cesium.ScreenSpaceEventType.LEFT_DOWN
    );
    this.viewer.screenSpaceEventHandler.setInputAction(
      _this.leftUpAction,
      Cesium.ScreenSpaceEventType.LEFT_UP
    );
    this.viewer.screenSpaceEventHandler.setInputAction(
      _this.mouseMoveAction,
      Cesium.ScreenSpaceEventType.MOUSE_MOVE
    );
  },
  watch: {
    test_positions: function() {
      console.log("a发生变化");
      var _positions = [];
      for (let m of this.test_positions) {
        var _position = {};

        var cartographic = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(
          m
        );
        _position.lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(4);
        _position.lng = Cesium.Math.toDegrees(cartographic.longitude).toFixed(4);
        _position.alt = cartographic.height.toFixed(4);
        console.log(_position);
        _positions.push(_position);
      }
      console.log(_positions)
      this.positionsForUse=_positions
    },
  },
  methods: {
    drawAirway() {
      this.$refs.marker.menuActionForAir("POLYLINE");
    },

    draw() {
      let Cesium = this.Cesium;
      let viewer = this.viewer;
      var drawTransformCurve = create({
        Cesium,
        viewer,
      });
      this.drawTransformCurve = drawTransformCurve;
      viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(117.224, 31.819, 300.0),
        orientation: {
          // 指向
          heading: 0.0,
          // 视角
          pitch: Cesium.Math.toRadians(-90),
          roll: 0.0,
        },
      });
      let position = this.position;
      let rotates = this.rotates;
      var _this = this;
      var fromDegposition = Cesium.Cartesian3.fromDegrees(
        position.lon,
        position.lat,
        position.alt
      );

      var pointd = viewer.entities.add({
        position: fromDegposition,
        point: {
          pixelSize: 5,
          color: Cesium.Color.fromCssColorString("rgba(255,0,0,0.5)"), //园的颜色
          outlineColor: Cesium.Color.fromCssColorString("rgba(255,255,255,1)"), //轮廓颜色
          outlineWidth: 1, //轮廓宽度
        },
      });
      // clearInterval(timer);
      var timer = setInterval(() => {
        drawTransformCurve.startTransfromEnt({
          id: "asjhfui",
          position,
          rotates,
          ifDrawLine: true,
        });
        position.lon += Math.random() * 0.0001;
        position.lat += Math.random() * 0.0001;
        position.alt += Math.random() * 1;
        rotates.heading += Math.random() * 10;
        rotates.pitch += Math.random() * 10;
        rotates.roll += Math.random() * 10;
      }, 10);
    },
    clear() {
      let Cesium = this.Cesium;
      let viewer = this.viewer;
      this.clear_visible = false;
      let travel = viewer.entities.getById("travel");
      viewer.entities.remove(travel);
      viewer.entities.removeAll();
    },
    clear1() {
      this.drawTransformCurve.clear();
    },
    focus() {
      let viewer = this.viewer;
      let Cesium = this.Cesium;
      viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(
          this.position.lon,
          this.position.lat,
          10000
        ),
        orientation: {
          // 指向
          heading: 0.0,
          // 视角
          pitch: Cesium.Math.toRadians(-90),
          roll: 0.0,
        },
      });

      viewer.trackedEntity = viewer.entities.getById("asjhfui");
    },
    goTo() {
      let viewer = this.viewer;
      let Cesium = this.Cesium;
      let _this = this;
      if (
        parseFloat(_this.in_lon) >= -180 &&
        parseFloat(_this.in_lon) <= 180 &&
        parseFloat(_this.in_lat) >= -90 &&
        parseFloat(_this.in_lat) <= 90
      ) {
        viewer.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            parseFloat(_this.in_lon),
            parseFloat(_this.in_lat),
            100000
          ), //经度、纬度、高度
          // orientation: {
          //    	heading: 0,
          //    	pitch: Cesium.Math.toRadians(-70.5 || -Cesium.Math.PI_OVER_FOUR),
          //    	roll: Cesium.Math.toRadians(360 || 0)
          // },
          duration: 3,
        });
      } else {
        alert("请输入正确的经纬度");
      }
    },
    // click() {
    //   let viewer = this.viewer;
    //   let Cesium = this.Cesium;
    //   var drawTransformCurve = create({
    //     Cesium,
    //     viewer,
    //   });
    //   this.drawTransformCurve = drawTransformCurve;
    //   let handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    //   let PolylineArr = [],
    //     params = { positions: [] },
    //     lastPoint,
    //     nextPoint;

    //   handler.setInputAction(function(event) {
    //     let earthPosition = viewer.camera.pickEllipsoid(
    //       event.position,
    //       viewer.scene.globe.ellipsoid
    //     );
    //     if (Cesium.defined(earthPosition)) {
    //       let ellipsoid = viewer.scene.globe.ellipsoid;
    //       let cartographic = ellipsoid.cartesianToCartographic(earthPosition);
    //       let lon = Cesium.Math.toDegrees(cartographic.longitude);
    //       let lat = Cesium.Math.toDegrees(cartographic.latitude);
    //       drawTransformCurve.AddPoint({
    //         lon: lon,
    //         lat: lat,
    //         color: Cesium.Color.YELLOW,
    //       });
    //       if (lastPoint === undefined) {
    //         lastPoint = new Cesium.Cartesian3.fromDegrees(lon, lat);
    //       } else {
    //         nextPoint = new Cesium.Cartesian3.fromDegrees(lon, lat);
    //         drawTransformCurve.AddPolyline({
    //           positions: [lastPoint, nextPoint],
    //         });
    //         lastPoint = nextPoint;
    //       }
    //     }
    //   }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //   this.handler = handler;
    // },
    finishAdd() {
      let Cesium = this.Cesium;
      let viewer = this.viewer;

      this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      //viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    computePositon() {
      let Cesium = this.Cesium;
      let viewer = this.viewer;
      var canvas = viewer.scene.canvas;
      var ellipsoid = viewer.scene.globe.ellipsoid;
      var handler = new Cesium.ScreenSpaceEventHandler(canvas);
      let _this = this;
      handler.setInputAction(function(movement) {
        var cartesian = viewer.camera.pickEllipsoid(
          movement.endPosition,
          ellipsoid
        );
        if (cartesian) {
          var cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(
            cartesian
          );
          _this.longitude = Cesium.Math.toDegrees(
            cartographic.longitude
          ).toFixed(4);
          _this.latitude = Cesium.Math.toDegrees(cartographic.latitude).toFixed(
            4
          );
          _this.altitude = (
            viewer.camera.positionCartographic.height / 1000
          ).toFixed(2);
          _this.elevation = viewer.scene.globe
            .getHeight(cartographic)
            .toFixed(4);
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
    showChina() {
      let Cesium = this.Cesium;
      let viewer = this.viewer;

      if (this.showChinas == true) {
        //viewer.scene.globe.depthTestAgainstTerrain = false;
        var datasource = new Cesium.GeoJsonDataSource.load("../../China.json", {
          stroke: Cesium.Color.RED,
          fill: Cesium.Color.YELLOW.withAlpha(0.5),
          strokeWidth: 5,
        });
        this.China = datasource.id;

        var datasource = viewer.dataSources.add(datasource);
      } else {
        console.log(viewer.dataSources);
        var length = viewer.dataSources.length;

        for (var i = 0; i < length; i++) {
          var data = viewer.dataSources.get(i);
          if (data._name && data._name == "China.json") {
            viewer.dataSources.remove(data);
          }
        }
      }
    },
    showBird() {
      this.showBirds = !this.showBirds;
    },
    beginBird() {
      let viewer = this.viewer;
      let Cesium = this.cesium;
      var viewer1 = new Cesium.Viewer("eye", {
        sceneMode: Cesium.SceneMode.SCENE2D,
        imageryProvider: new this.Cesium.UrlTemplateImageryProvider({
          url:
            "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
        }),
        navigationHelpButton: false, //控制右上角第五个位置的导航帮助按钮
        animation: false, //控制左下角的动画器件
        timeline: false, //控制下方时间线
        baseLayerPicker: false,
        timeline: false,
        homeButton: false,
        fullscreenButton: false,
        infoBox: false,
        sceneModePicker: false,
        navigationInstructionsInitiallyVisible: false,
        navigationHelpButton: false,
        shouldAnimate: false,
        geocoder: false,
      });
      let control = viewer1.scene.screenSpaceCameraController;
      control.enableRotate = false;
      control.enableTranslate = false;
      control.enableZoom = false;
      control.enableTilt = false;
      control.enableLook = false;
      let syncViewer = function() {
        viewer1.camera.flyTo({
          destination: viewer.camera.position,
          orientation: {
            heading: viewer.camera.heading,
            pitch: viewer.camera.pitch,
            roll: viewer.camera.roll,
          },
          duration: 0.0,
        });
      };
      viewer1._cesiumWidget._creditContainer.style.display = "none";
      viewer.scene.preRender.addEventListener(syncViewer);
    },
    // drawPoint: function(callback) {
    //   let Cesium = this.Cesium;
    //   let viewer = this.viewer;
    //   var _this = this;
    //   //坐标存储
    //   var positions = [];

    //   var handler = new Cesium.ScreenSpaceEventHandler(
    //     _this.viewer.scene.canvas
    //   );

    //   //单击鼠标左键画点
    //   handler.setInputAction(function(movement) {
    //     var cartesian = _this.viewer.scene.camera.pickEllipsoid(
    //       movement.position,
    //       _this.viewer.scene.globe.ellipsoid
    //     );
    //     positions.push(cartesian);

    //     var entity=_this.viewer.entities.add({
    //       position: cartesian,
    //       // point: {
    //       //     color: Cesium.Color.RED,
    //       //     pixelSize: 5,
    //       //     heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
    //       // }
    //       billboard: {
    //         // 图像地址，URI或Canvas的属性
    //         image: "../../static/images/B.png",
    //         // 设置颜色和透明度
    //         color: Cesium.Color.WHITE.withAlpha(0.8),
    //         // 高度（以像素为单位）
    //         height: 50,
    //         // 宽度（以像素为单位）
    //         width: 50,
    //         // 逆时针旋转
    //         rotation: 0,
    //         // 大小是否以米为单位
    //         sizeInMeters: false,
    //         // 相对于坐标的垂直位置
    //         verticalOrigin: Cesium.VerticalOrigin.CENTER,
    //         // 相对于坐标的水平位置
    //         horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
    //         // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
    //         pixelOffset: new Cesium.Cartesian2(-20, -20),
    //         // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
    //         scale: 1.0,
    //         // 是否显示
    //         show: true,
    //       },
    //     });
    //     _this.point_positions.push(entity)
    //   }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //   //单击鼠标右键结束画点
    //   handler.setInputAction(function(movement) {
    //   //  callback(positions);
    //     handler.destroy();
    //   }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    // },
    //画线
    drawLineString: function(callback) {
      let Cesium = this.Cesium;
      let viewer = this.viewer;
      var _this = this;
      var PolyLinePrimitive = (function() {
        function _(positions) {
          this.options = {
            polyline: {
              show: true,
              positions: [],
              material: Cesium.Color.RED,
              width: 3,
            },
          };
          this.positions = positions;
          this._init();
        }

        _.prototype._init = function() {
          var _self = this;
          var _update = function() {
            return _this.test_positions;
          };
          //实时更新polyline.positions
          this.options.polyline.positions = new Cesium.CallbackProperty(
            _update,
            false
          );
          _this.viewer.entities.add(this.options);
        };
        return _;
      })();

      var handler = new Cesium.ScreenSpaceEventHandler(
        _this.viewer.scene.canvas
      );
      //var positions = [];
      var poly = undefined;
      //鼠标左键单击画点
      handler.setInputAction(function(movement) {
        var cartesian = _this.viewer.scene.camera.pickEllipsoid(
          movement.position,
          _this.viewer.scene.globe.ellipsoid
        );
        var entity = _this.viewer.entities.add({
          position: cartesian,
          point: {
            color: Cesium.Color.WHITE,
            pixelSize: 20,
            heightReference: Cesium.HeightReference.NONE,
          },
          // billboard: {
          //   // 图像地址，URI或Canvas的属性
          //   image: "../../static/images/B.png",
          //   // 设置颜色和透明度
          //   color: Cesium.Color.WHITE.withAlpha(0.8),
          //   // 高度（以像素为单位）
          //   height: 50,
          //   // 宽度（以像素为单位）
          //   width: 50,
          //   // 逆时针旋转
          //   rotation: 0,
          //   // 大小是否以米为单位
          //   sizeInMeters: false,
          //   // 相对于坐标的垂直位置
          //   verticalOrigin: Cesium.VerticalOrigin.CENTER,
          //   // 相对于坐标的水平位置
          //   horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          //   // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
          //   pixelOffset: new Cesium.Cartesian2(0, 0),
          //   // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
          //   scale: 1.0,
          //   // 是否显示
          //   show: true,
          // },
        });
        _this.point_positions.push(entity.id);
        let linePositions = [];

        let temp = _this.Cartesian3_to_WGS84(cartesian);
        linePositions.push(
          new Cesium.Cartesian3.fromDegrees(temp.lng, temp.lat, temp.alt)
        );
        linePositions.push(
          new Cesium.Cartesian3.fromDegrees(temp.lng, temp.lat, 0)
        );
        //   _this.ErectLinePositions
        _this.viewer.entities.add({
          id: "erect" + entity.id,
          polyline: {
            positions: linePositions,
            width: 1.5,
            material: Cesium.Color.WHITE.withAlpha(0.8),
          },
        });

        if (_this.test_positions.length == 0) {
          _this.test_positions.push(cartesian.clone());
        }

        // if (_this.test_positions.length == 2) {
        //   new PolyLinePrimitive(_this.test_positions);
        // }
        _this.test_positions.push(cartesian);
      }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
      //   鼠标移动
      handler.setInputAction(function(movement) {
        var cartesian = _this.viewer.scene.camera.pickEllipsoid(
          movement.endPosition,
          _this.viewer.scene.globe.ellipsoid
        );
        if (_this.test_positions.length >= 2) {
          if (!Cesium.defined(poly)) {
            poly = new PolyLinePrimitive(_this.test_positions);
          } else {
            if (cartesian != undefined) {
              _this.test_positions.pop();
              cartesian.y += 1 + Math.random();
              _this.test_positions.push(cartesian);
            }
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      //单击鼠标右键结束画线
      handler.setInputAction(function(movement) {
        // var cartesian = _this.viewer.scene.camera.pickEllipsoid(
        //   movement.position,
        //   _this.viewer.scene.globe.ellipsoid
        // );
        // var entity = _this.viewer.entities.add({
        //   position: cartesian,
        //   point: {
        //       color: Cesium.Color.WHITE,
        //       pixelSize: 10,
        //       heightReference: Cesium.HeightReference.NONE
        //   }
        //   // billboard: {
        //   //   // 图像地址，URI或Canvas的属性
        //   //   image: "../../static/images/B.png",
        //   //   // 设置颜色和透明度
        //   //   color: Cesium.Color.WHITE.withAlpha(0.8),
        //   //   // 高度（以像素为单位）
        //   //   height: 50,
        //   //   // 宽度（以像素为单位）
        //   //   width: 50,
        //   //   // 逆时针旋转
        //   //   rotation: 0,
        //   //   // 大小是否以米为单位
        //   //   sizeInMeters: false,
        //   //   // 相对于坐标的垂直位置
        //   //   verticalOrigin: Cesium.VerticalOrigin.CENTER,
        //   //   // 相对于坐标的水平位置
        //   //   horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
        //   //   // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
        //   //   pixelOffset: new Cesium.Cartesian2(-20, -20),
        //   //   // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
        //   //   scale: 1.0,
        //   //   // 是否显示
        //   //   show: true,
        //   // },
        // });
        // _this.point_positions.push(entity.id);
        _this.test_positions.pop();
        handler.destroy();
        //   callback(positions);
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      console.log(_this.test_positions);
    },
    //画面
    drawPolygon: function(callback) {
      let Cesium = this.Cesium;
      var _this = this;
      var PolygonPrimitive = (function() {
        function _(positions) {
          this.options = {
            name: "多边形",
            polygon: {
              hierarchy: [],
              perPositionHeight: true,
              material: Cesium.Color.RED.withAlpha(0.4),
            },
          };
          this.hierarchy = new Cesium.PolygonHierarchy(positions);
          this._init();
        }

        _.prototype._init = function() {
          var _self = this;
          var _update = function() {
            return _self.hierarchy;
          };
          //实时更新polygon.hierarchy
          this.options.polygon.hierarchy = new Cesium.CallbackProperty(
            _update,
            false
          );
          _this.viewer.entities.add(this.options);
        };
        return _;
      })();

      var handler = new Cesium.ScreenSpaceEventHandler(
        _this.viewer.scene.canvas
      );
      var positions = [];
      var poly = undefined;

      //鼠标单击画点
      handler.setInputAction(function(movement) {
        var cartesian = _this.viewer.scene.camera.pickEllipsoid(
          movement.position,
          _this.viewer.scene.globe.ellipsoid
        );
        if (positions.length == 0) {
          positions.push(cartesian.clone());
        }
        positions.push(cartesian);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      //鼠标移动
      handler.setInputAction(function(movement) {
        var cartesian = _this.viewer.scene.camera.pickEllipsoid(
          movement.endPosition,
          _this.viewer.scene.globe.ellipsoid
        );
        if (positions.length >= 2) {
          if (!Cesium.defined(poly)) {
            poly = new PolygonPrimitive(positions);
          } else {
            if (cartesian != undefined) {
              positions.pop();
              cartesian.y += 1 + Math.random();
              positions.push(cartesian);
            }
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      //鼠标右键单击结束绘制
      handler.setInputAction(function(movement) {
        handler.destroy();
        callback(positions);
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    },
    //画圆
    circleDraw(_callBack) {
      let Cesium = this.Cesium;
      let _self = this;
      _self.viewer.scene.globe.depthTestAgainstTerrain = false;
      let circle = {
        points: [],
        rect: null,
        entity: null,
        r: 1,
      };
      var tempPosition;
      let cartographic1;
      let p;
      let tempLon;
      let tempLat;
      var ShapeEventHandler = new Cesium.ScreenSpaceEventHandler(
        _self.viewer.scene.canvas
      );
      //common.handlerList.push(ShapeEventHandler);
      ShapeEventHandler.setInputAction(function(click) {
        tempPosition = _self.getPointFromWindowPoint(click.position);

        //选择的点在球面上
        if (tempPosition) {
          function callBackPos() {
            const minlon = Cesium.Math.toDegrees(circle.points[0].longitude);
            const minlat = Cesium.Math.toDegrees(circle.points[0].latitude);
            const maxlon = Cesium.Math.toDegrees(circle.points[1].longitude);
            const maxlat = Cesium.Math.toDegrees(circle.points[1].latitude);
            let r = _self.getFlatternDistance(minlat, minlon, maxlat, maxlon);
            if (r) {
              return r;
            }
            return 1;
          }
          if (circle.points.length == 0) {
            p = click.position;
            cartographic1 = Cesium.Ellipsoid.WGS84.cartesianToCartographic(
              tempPosition
            );
            circle.points.push(
              _self.viewer.scene.globe.ellipsoid.cartesianToCartographic(
                tempPosition
              )
            );
            circle.points.push(
              _self.viewer.scene.globe.ellipsoid.cartesianToCartographic(
                tempPosition
              )
            );
            tempLon = Cesium.Math.toDegrees(cartographic1.longitude);
            tempLat = Cesium.Math.toDegrees(cartographic1.latitude);
            circle.entity = _self.viewer.entities.add({
              position: Cesium.Cartesian3.fromDegrees(tempLon, tempLat),
              ellipse: {
                semiMinorAxis: new Cesium.CallbackProperty(callBackPos, false),
                semiMajorAxis: new Cesium.CallbackProperty(callBackPos, false),
                //条形材质
                material: Cesium.Color.RED.withAlpha(0.3),
              },
            });
          } else {
            ShapeEventHandler.removeInputAction(
              Cesium.ScreenSpaceEventType.MOUSE_MOVE
            );
            ShapeEventHandler.removeInputAction(
              Cesium.ScreenSpaceEventType.LEFT_CLICK
            );

            // ShapeEventHandler.removeInputAction(
            //   Cesium.ScreenSpaceEventType.MOUSE_MOVE
            // );
            // ShapeEventHandler.removeInputAction(
            //   Cesium.ScreenSpaceEventType.LEFT_CLICK
            // );
            // var tempCircle = new Cesium.CircleOutlineGeometry({
            //   center: Cesium.Cartesian3.fromDegrees(tempLon, tempLat),
            //   radius: callBackPos(),
            //   granularity: Math.PI / 2,
            // });
            // var geometry = Cesium.CircleOutlineGeometry.createGeometry(
            //   tempCircle
            // );
            // var float64ArrayPositionsIn = geometry.attributes.position.values;
            // var positionsIn = [].slice.call(float64ArrayPositionsIn);
            // _callBack(positionsIn);
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      ShapeEventHandler.setInputAction(function(movement) {
        if (circle.points.length == 0) {
          return;
        }
        var moveEndPosition = _self.getPointFromWindowPoint(
          movement.endPosition
        );
        //选择的点在球面上
        if (moveEndPosition) {
          circle.points.pop();
          circle.points.push(
            _self.viewer.scene.globe.ellipsoid.cartesianToCartographic(
              moveEndPosition
            )
          );
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
    //画矩形
    drawRect: function(callback) {
      let Cesium = this.Cesium;
      let _self = this;
      let pointsArr = [];
      _self.shape = {
        points: [],
        rect: null,
        entity: null,
      };
      var tempPosition;
      var handle = new Cesium.ScreenSpaceEventHandler(
        _self.viewer.scene.canvas
      );
      //鼠标左键单击画点
      handle.setInputAction(function(click) {
        tempPosition = _self.getPointFromWindowPoint(click.position);
        //选择的点在球面上
        if (tempPosition) {
          if (_self.shape.points.length == 0) {
            pointsArr.push(tempPosition);
            _self.shape.points.push(
              _self.viewer.scene.globe.ellipsoid.cartesianToCartographic(
                tempPosition
              )
            );
            _self.shape.rect = Cesium.Rectangle.fromCartographicArray(
              _self.shape.points
            );
            _self.shape.rect.east += 0.000001;
            _self.shape.rect.north += 0.000001;
            _self.shape.entity = _self.viewer.entities.add({
              rectangle: {
                coordinates: _self.shape.rect,
                material: Cesium.Color.BLACK.withAlpha(0.4),
                outline: true,
                outlineWidth: 2,
                outlineColor: Cesium.Color.RED,
                height: 0,
              },
            });
            _self.bufferEntity = _self.shape.entity;
          } else {
            handle.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
            handle.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
            callback(pointsArr);
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      //鼠标移动
      handle.setInputAction(function(movement) {
        if (_self.shape.points.length == 0) {
          return;
        }
        var moveEndPosition = _self.getPointFromWindowPoint(
          movement.endPosition
        );
        //选择的点在球面上
        if (moveEndPosition) {
          pointsArr[1] = moveEndPosition;
          _self.shape.points[1] = _self.viewer.scene.globe.ellipsoid.cartesianToCartographic(
            moveEndPosition
          );
          _self.shape.rect = Cesium.Rectangle.fromCartographicArray(
            _self.shape.points
          );
          if (_self.shape.rect.west == _self.shape.rect.east)
            _self.shape.rect.east += 0.000001;
          if (_self.shape.rect.south == _self.shape.rect.north)
            _self.shape.rect.north += 0.000001;
          _self.shape.entity.rectangle.coordinates = _self.shape.rect;
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
    //清除所有Entity和ImageryLayers
    clearHandle: function() {
      let Cesium = this.Cesium;
      //移除所有实体Entity
      this.viewer.entities.removeAll();
      //移除cesium加载的ImageryLayer
      for (var i = 0; i < this.removeImageryLayers.length; i++) {
        this.viewer.imageryLayers.remove(this.removeImageryLayers[i]);
      }
    },
    getPointFromWindowPoint(point) {
      let viewer = this.viewer;
      if (
        viewer.scene.terrainProvider.constructor.name ==
        "EllipsoidTerrainProvider"
      ) {
        return viewer.camera.pickEllipsoid(point, viewer.scene.globe.ellipsoid);
      } else {
        var ray = viewer.scene.camera.getPickRay(point);
        return viewer.scene.globe.pick(ray, viewer.scene);
      }
    },
    //笛卡尔坐标系转WGS84坐标系
    Cartesian3_to_WGS84: function(point) {
      let Cesium = this.cesium;
      var cartesian33 = new Cesium.Cartesian3(point.x, point.y, point.z);
      console.log(cartesian33);
      console.log("123456");
      var cartographic = Cesium.Cartographic.fromCartesian(cartesian33);
      // var cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(
      //         cartesian33
      //       );
      console.log(cartographic);
      console.log("654321");
      var lat = Cesium.Math.toDegrees(cartographic.latitude);
      var lng = Cesium.Math.toDegrees(cartographic.longitude);
      var alt = cartographic.height;
      return { lat: lat, lng: lng, alt: alt };
    },
    //WGS84坐标系转笛卡尔坐标系
    WGS84_to_Cartesian3: function(point) {
      let Cesium = this.cesium;
      var car33 = Cesium.Cartesian3.fromDegrees(
        parseFloat(point.lng) ,
        parseFloat(point.lat),
        parseFloat(point.alt)
      );
      var x = car33.x;
      var y = car33.y;
      var z = car33.z;
      return { x: x, y: y, z: z };
    },

    //计算两点间距离
    getFlatternDistance(lat1, lng1, lat2, lng2) {
      var EARTH_RADIUS = 6378137.0; //单位M
      var PI = Math.PI;

      function getRad(d) {
        return (d * PI) / 180.0;
      }
      var f = getRad((lat1 + lat2) / 2);
      var g = getRad((lat1 - lat2) / 2);
      var l = getRad((lng1 - lng2) / 2);

      var sg = Math.sin(g);
      var sl = Math.sin(l);
      var sf = Math.sin(f);

      var s, c, w, r, d, h1, h2;
      var a = EARTH_RADIUS;
      var fl = 1 / 298.257;

      sg = sg * sg;
      sl = sl * sl;
      sf = sf * sf;

      s = sg * (1 - sl) + (1 - sf) * sl;
      c = (1 - sg) * (1 - sl) + sf * sl;

      w = Math.atan(Math.sqrt(s / c));
      r = Math.sqrt(s * c) / w;
      d = 2 * w * a;
      h1 = (3 * r - 1) / 2 / c;
      h2 = (3 * r + 1) / 2 / s;

      return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
    },

    selectPlane() {
      let Cesium = this.cesium;

      if (this.plane1 == false) {
        this.plane1 = true;
        document.getElementsByClassName("planebox")[0].style.border =
          "1px solid red";
        document.getElementsByClassName("planebox")[0].style.backgroundColor =
          "blue";

        var _this = this;
        //坐标存储
        var positions = [];

        var handler = new Cesium.ScreenSpaceEventHandler(
          _this.viewer.scene.canvas
        );

        //单击鼠标左键画点
        handler.setInputAction(function(movement) {
          var cartesian = _this.viewer.scene.camera.pickEllipsoid(
            movement.position,
            _this.viewer.scene.globe.ellipsoid
          );
          positions.push(cartesian);
          console.log("viewrhere");
          console.log(cartesian);
          _this.viewer.entities.add({
            position: cartesian,
            // point: {
            //     color: Cesium.Color.RED,
            //     pixelSize: 5,
            //     heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            // }
            model: {
              // 图像地址，URI或Canvas的属性
              uri: "./static/model/scene.gltf ",
              minimumPixelSize: 128,
              // 设置颜色和透明度
              // color: Cesium.Color.WHITE.withAlpha(0.8),
              // // 高度（以像素为单位）
              // height: 50,
              // // 宽度（以像素为单位）
              // width: 50,
              // // 逆时针旋转
              // rotation: 0,
              // // 大小是否以米为单位
              // sizeInMeters: false,
              // // 相对于坐标的垂直位置
              // verticalOrigin: Cesium.VerticalOrigin.CENTER,
              // // 相对于坐标的水平位置
              // horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
              // // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
              // pixelOffset: new Cesium.Cartesian2(-20, -20),
              // // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
              // scale: 1.0,
              // // 是否显示
            },
          });
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        //单击鼠标右键结束画点
        handler.setInputAction(function(movement) {
          handler.destroy();
          _this.plane1 = false;
          document.getElementsByClassName("planebox")[0].style.border = "";
          document.getElementsByClassName("planebox")[0].style.backgroundColor =
            "";
          callback(positions);
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      } else {
      }
    },

    measureLineSpace() {
      // 取消双击事件-追踪该位置
      let Cesium = this.cesium;
      let viewer = this.viewer;
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );

      var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      var positions = [];
      var poly = null;
      // var tooltip = document.getElementById("toolTip");
      var distance = 0;
      var cartesian = null;
      var floatingPoint;
      // tooltip.style.display = "block";

      handler.setInputAction(function(movement) {
        // tooltip.style.left = movement.endPosition.x + 3 + "px";
        // tooltip.style.top = movement.endPosition.y - 25 + "px";
        // tooltip.innerHTML = '<p>单击开始，右击结束</p>';
        // cartesian = viewer.scene.pickPosition(movement.endPosition);
        let ray = viewer.camera.getPickRay(movement.endPosition);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        //cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
        if (positions.length >= 2) {
          if (!Cesium.defined(poly)) {
            poly = new PolyLinePrimitive(positions);
          } else {
            positions.pop();
            // cartesian.y += (1 + Math.random());
            positions.push(cartesian);
          }
          distance = getSpaceDistance(positions);
          // console.log("distance: " + distance);
          // tooltip.innerHTML='<p>'+distance+'米</p>';
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      handler.setInputAction(function(movement) {
        // tooltip.style.display = "none";
        // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
        // cartesian = viewer.scene.pickPosition(movement.position);
        let ray = viewer.camera.getPickRay(movement.position);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        if (positions.length == 0) {
          positions.push(cartesian.clone());
        }
        positions.push(cartesian);
        //在三维场景中添加Label
        //   var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var textDisance = distance + "米";
        // console.log(textDisance + ",lng:" + cartographic.longitude/Math.PI*180.0);
        floatingPoint = viewer.entities.add({
          name: "空间直线距离",
          // position: Cesium.Cartesian3.fromDegrees(cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180,cartographic.height),
          position: positions[positions.length - 1],
          point: {
            pixelSize: 5,
            color: Cesium.Color.RED,
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 2,
          },
          label: {
            text: textDisance,
            font: "18px sans-serif",
            fillColor: Cesium.Color.GOLD,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            outlineWidth: 2,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(20, -20),
          },
        });
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      handler.setInputAction(function(movement) {
        handler.destroy(); //关闭事件句柄
        positions.pop(); //最后一个点无效
        // viewer.entities.remove(floatingPoint);
        // tooltip.style.display = "none";
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

      var PolyLinePrimitive = (function() {
        function _(positions) {
          this.options = {
            name: "直线",
            polyline: {
              show: true,
              positions: [],
              material: Cesium.Color.CHARTREUSE,
              width: 10,
              clampToGround: true,
            },
          };
          this.positions = positions;
          this._init();
        }

        _.prototype._init = function() {
          var _self = this;
          var _update = function() {
            return _self.positions;
          };
          //实时更新polyline.positions
          this.options.polyline.positions = new Cesium.CallbackProperty(
            _update,
            false
          );
          viewer.entities.add(this.options);
        };

        return _;
      })();

      //空间两点距离计算函数
      function getSpaceDistance(positions) {
        var distance = 0;
        for (var i = 0; i < positions.length - 1; i++) {
          var point1cartographic = Cesium.Cartographic.fromCartesian(
            positions[i]
          );
          var point2cartographic = Cesium.Cartographic.fromCartesian(
            positions[i + 1]
          );
          /**根据经纬度计算出距离**/
          var geodesic = new Cesium.EllipsoidGeodesic();
          geodesic.setEndPoints(point1cartographic, point2cartographic);
          var s = geodesic.surfaceDistance;
          //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
          //返回两点之间的距离
          s = Math.sqrt(
            Math.pow(s, 2) +
              Math.pow(point2cartographic.height - point1cartographic.height, 2)
          );
          distance = distance + s;
        }
        return distance.toFixed(2);
      }
    },

    //****************************测量空间面积************************************************//
    measureAreaSpace() {
      let Cesium = this.cesium;
      let viewer = this.viewer;
      // 取消双击事件-追踪该位置
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );
      // 鼠标事件
      var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      var positions = [];
      var tempPoints = [];
      var polygon = null;
      // var tooltip = document.getElementById("toolTip");
      var cartesian = null;
      var floatingPoint; //浮动点
      // tooltip.style.display = "block";

      handler.setInputAction(function(movement) {
        // tooltip.style.left = movement.endPosition.x + 3 + "px";
        // tooltip.style.top = movement.endPosition.y - 25 + "px";
        // tooltip.innerHTML ='<p>单击开始，右击结束</p>';
        // cartesian = viewer.scene.pickPosition(movement.endPosition);
        let ray = viewer.camera.getPickRay(movement.endPosition);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        //cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
        if (positions.length >= 2) {
          if (!Cesium.defined(polygon)) {
            polygon = new PolygonPrimitive(positions);
          } else {
            positions.pop();
            // cartesian.y += (1 + Math.random());
            positions.push(cartesian);
          }
          // tooltip.innerHTML='<p>'+distance+'米</p>';
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      handler.setInputAction(function(movement) {
        // tooltip.style.display = "none";
        // cartesian = viewer.scene.pickPosition(movement.position);
        let ray = viewer.camera.getPickRay(movement.position);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
        if (positions.length == 0) {
          positions.push(cartesian.clone());
        }
        //positions.pop();
        positions.push(cartesian);
        //在三维场景中添加点
        var cartographic = Cesium.Cartographic.fromCartesian(
          positions[positions.length - 1]
        );
        var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
        var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
        var heightString = cartographic.height;
        tempPoints.push({
          lon: longitudeString,
          lat: latitudeString,
          hei: heightString,
        });
        floatingPoint = viewer.entities.add({
          name: "多边形面积",
          position: positions[positions.length - 1],
          point: {
            pixelSize: 5,
            color: Cesium.Color.RED,
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 2,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          },
        });
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      handler.setInputAction(function(movement) {
        handler.destroy();
        positions.pop();
        //tempPoints.pop();
        // viewer.entities.remove(floatingPoint);
        // tooltip.style.display = "none";
        //在三维场景中添加点
        // var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1]);
        // var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
        // var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
        // var heightString = cartographic.height;
        // tempPoints.push({ lon: longitudeString, lat: latitudeString ,hei:heightString});

        var textArea = getArea(tempPoints) + "平方公里";
        viewer.entities.add({
          name: "多边形面积",
          position: positions[positions.length - 1],
          // point : {
          //  pixelSize : 5,
          //  color : Cesium.Color.RED,
          //  outlineColor : Cesium.Color.WHITE,
          //  outlineWidth : 2,
          //  heightReference:Cesium.HeightReference.CLAMP_TO_GROUND
          // },
          label: {
            text: textArea,
            font: "18px sans-serif",
            fillColor: Cesium.Color.GOLD,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            outlineWidth: 2,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(20, -40),
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          },
        });
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

      var radiansPerDegree = Math.PI / 180.0; //角度转化为弧度(rad)
      var degreesPerRadian = 180.0 / Math.PI; //弧度转化为角度

      //计算多边形面积
      function getArea(points) {
        var res = 0;
        //拆分三角曲面

        for (var i = 0; i < points.length - 2; i++) {
          var j = (i + 1) % points.length;
          var k = (i + 2) % points.length;
          var totalAngle = Angle(points[i], points[j], points[k]);

          var dis_temp1 = distance(positions[i], positions[j]);
          var dis_temp2 = distance(positions[j], positions[k]);
          res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle));
          console.log(res);
        }

        return (res / 1000000.0).toFixed(4);
      }

      /*角度*/
      function Angle(p1, p2, p3) {
        var bearing21 = Bearing(p2, p1);
        var bearing23 = Bearing(p2, p3);
        var angle = bearing21 - bearing23;
        if (angle < 0) {
          angle += 360;
        }
        return angle;
      }
      /*方向*/
      function Bearing(from, to) {
        var lat1 = from.lat * radiansPerDegree;
        var lon1 = from.lon * radiansPerDegree;
        var lat2 = to.lat * radiansPerDegree;
        var lon2 = to.lon * radiansPerDegree;
        var angle = -Math.atan2(
          Math.sin(lon1 - lon2) * Math.cos(lat2),
          Math.cos(lat1) * Math.sin(lat2) -
            Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)
        );
        if (angle < 0) {
          angle += Math.PI * 2.0;
        }
        angle = angle * degreesPerRadian; //角度
        return angle;
      }

      var PolygonPrimitive = (function() {
        function _(positions) {
          this.options = {
            name: "多边形",
            polygon: {
              hierarchy: [],
              // perPositionHeight : true,
              material: Cesium.Color.GREEN.withAlpha(0.5),
              // heightReference:20000
            },
          };

          this.hierarchy = { positions };
          this._init();
        }

        _.prototype._init = function() {
          var _self = this;
          var _update = function() {
            return _self.hierarchy;
          };
          //实时更新polygon.hierarchy
          this.options.polygon.hierarchy = new Cesium.CallbackProperty(
            _update,
            false
          );
          viewer.entities.add(this.options);
        };

        return _;
      })();

      function distance(point1, point2) {
        var point1cartographic = Cesium.Cartographic.fromCartesian(point1);
        var point2cartographic = Cesium.Cartographic.fromCartesian(point2);
        /**根据经纬度计算出距离**/
        var geodesic = new Cesium.EllipsoidGeodesic();
        geodesic.setEndPoints(point1cartographic, point2cartographic);
        var s = geodesic.surfaceDistance;
        //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
        //返回两点之间的距离
        s = Math.sqrt(
          Math.pow(s, 2) +
            Math.pow(point2cartographic.height - point1cartographic.height, 2)
        );
        return s;
      }
    },
    changePosition(index) {
      let positions = this.positionsForUse;
      
      console.log(positions);
      var c_positions = [];
      var ellipsoid = this.viewer.scene.globe.ellipsoid;
      for (let m of positions) {

        var cartographic = Cesium.Cartographic.fromDegrees(parseFloat(m.lng), parseFloat(m.lat), parseFloat(m.alt));
        var cartesian3 = ellipsoid.cartographicToCartesian(cartographic);
        c_positions.push(cartesian3);
      }
     this.test_positions=c_positions
     console.log(this.point_positions[index])
     var entity=this.viewer.entities.getById(this.point_positions[index])
    console.log(entity)
      var _cartographic = Cesium.Cartographic.fromDegrees(parseFloat(this.positionsForUse[index].lng), parseFloat(this.positionsForUse[index].lat), parseFloat(this.positionsForUse[index].alt));
      var _cartesian3 = ellipsoid.cartographicToCartesian(_cartographic);
      
     entity.position=_cartesian3

    var erectentity=this.viewer.entities.getById("erect"+entity.id)
          let _this=this
          console.log(erectentity)
          //cartesian=_this.WGS84_to_Cartesian3()
          let linePositions = [];
         
          linePositions.push(
            new Cesium.Cartesian3.fromDegrees(parseFloat(_this.positionsForUse[index].lng) ,parseFloat( _this.positionsForUse[index].lat), parseFloat(_this.positionsForUse[index].alt))
          );
          linePositions.push(
            new Cesium.Cartesian3.fromDegrees(parseFloat(_this.positionsForUse[index].lng), parseFloat(_this.positionsForUse[index].lat), 0)
          );
       //   console.log(erectnumber);
          if (erectentity) {
            erectentity.polyline.positions = linePositions
          }


    },
    leftDownAction(e) {
      let viewer = this.viewer;
      console.log("左键按下");
      this.pointDraged = viewer.scene.drillPick(e.position); //选取当前的entity
      this.leftDownFlag = true;
      if (this.pointDraged.length != 0) {
        viewer.scene.screenSpaceCameraController.enableRotate = false; //锁定相机
      }
    },
    leftUpAction(e) {
      let viewer = this.viewer;
      console.log("左键抬起");
      this.leftDownFlag = false;
      this.pointDraged = [];
      viewer.scene.screenSpaceCameraController.enableRotate = true; //解锁相机
    },
    mouseMoveAction(e) {
      let Cesium = this.Cesium;
      let viewer = this.viewer;
      var temp = -1;
      if (this.leftDownFlag === true && this.pointDraged.length != 0) {
        console.log("鼠标移动");
        var ray = viewer.camera.getPickRay(e.endPosition);
        var cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        console.log(cartesian);

        for (var i = 0; i < this.point_positions.length; i++) {
          for (var j = 0; j < this.pointDraged.length; j++) {
            if (this.pointDraged[j].id._id == this.point_positions[i]) {
              temp = j;
              this.record = i;
              break;
            }
          }
        }
        console.log(this.pointDraged);
        // console.log(
        //   record +
        //     " " +
        //     this.pointDraged.id +
        //     " " +
        //     this.point_positions[record]
        // );

        if (this.record != -1) {
          this.test_positions[this.record] = cartesian;

          this.pointDraged[temp].id.position = new Cesium.CallbackProperty(
            function() {
              return cartesian;
            },
            false
          );
          var erectentity=this.viewer.entities.getById("erect"+this.pointDraged[temp].id._id)
          let _this=this
          console.log(erectentity)
       //   console.log(erectnumber);
          if (erectentity) {
            erectentity.polyline.positions = new Cesium.CallbackProperty(function() {
              let linePositions = [];
              let temp = _this.Cartesian3_to_WGS84(cartesian);
              linePositions.push(
                new Cesium.Cartesian3.fromDegrees(temp.lng, temp.lat, temp.alt)
              );
              linePositions.push(
                new Cesium.Cartesian3.fromDegrees(temp.lng, temp.lat, 0)
              );
              return linePositions
            }, false);
          }
        }

        this.record = -1;
        //此处根据具体entity来处理，也可能是pointDraged.id.position=cartesian;
      }
    },
  },
};
</script>
<style>
html,
body,
#container,
#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  position: relative;
}

#position {
  width: 100%;
  height: 50px;
  position: absolute;
  bottom: 30px;
  padding-left: 50px;
  color: white;
  right: 0;
  background-color: rgba(20, 19, 19, 0.849);
}

#position div {
  width: 300px;
  float: left;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.menubox {
  position: absolute;
  z-index: 5;
  left: 20px;
  top: 100px;
}
#eye {
  position: absolute;
  width: 20%;
  height: 40%;
  bottom: 0;
  right: 0;
  z-index: 999;
  background: red;
  border: solid blue 1px;
}
.planebox {
  width: 45px;
}
</style>
